package com.example.partner.fragment.find;

import static android.content.ContentValues.TAG;
import static android.content.Context.MODE_PRIVATE;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.partner.R;
import com.example.partner.adapter.find.PostAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.listener.EndlessScrollListener;
import com.example.partner.model.domain.Post;
import com.example.partner.model.vo.ScrollResult;
import com.example.partner.service.PostService;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class FellowFragment extends Fragment {
    private List<Post> postList = new ArrayList<>(); // 定义列表用于保存所有帖子数据
    private PostAdapter adapter; // 适配器
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    // Add these two variables
    private long max = System.currentTimeMillis();
    private int offset = 0;
    public FellowFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_find_fellow, container, false);
        swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        recyclerView = rootView.findViewById(R.id.recyclerViewFellow);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        recyclerView.setLayoutManager(layoutManager);
        // Create or update the adapter with an empty list
        adapter = new PostAdapter(postList, requireContext());
        recyclerView.setAdapter(adapter);
        loadMoreData();
        EndlessScrollListener endlessScrollListener = new EndlessScrollListener(layoutManager, new EndlessScrollListener.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                // 在这里更新
                loadMoreData();
            }
        });
        swipeRefreshLayout.setOnRefreshListener(() -> {
            refreshData();
        });
        recyclerView.addOnScrollListener(endlessScrollListener);


        return rootView;
    }

    /**
     * 加载数据
     */
    private void loadMoreData() {
        // 发请求
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        SharedPreferences sharedPreferences = requireContext().getSharedPreferences("CurrentUser", MODE_PRIVATE);
        Long userId = sharedPreferences.getLong("userId", -1);
        Call<BaseResponse<ScrollResult>> call = postService.queryPostOfFollow(max,offset,userId);
        call.enqueue(new Callback<BaseResponse<ScrollResult>>() {
            @Override
            public void onResponse(Call<BaseResponse<ScrollResult>> call, Response<BaseResponse<ScrollResult>> response) {
                if (response.isSuccessful()) {
                    if (response.body().getData()!=null&&response.body().getData().getList()!=null){
                        List<Post> newPostList = response.body().getData().getList();
                        max = response.body().getData().getMinTime();
                        offset = response.body().getData().getOffset();
                        postList.addAll(newPostList);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    // 处理错误情况
                    Log.d(TAG, "onResponse:fail");
                }
            }
            @Override
            public void onFailure(Call<BaseResponse<ScrollResult>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }

    /**
     * 刷新数据，重新加载
     */
    private void refreshData() {
        // Reset max and offset for a fresh load
        max = System.currentTimeMillis();
        offset = 0;
        // Clear the existing data
        postList.clear();
        // Load new data
        loadMoreData();
        swipeRefreshLayout.setRefreshing(false);
    }
}
